<!--
 * @Description: 编辑服务
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-07-03 11:41:05
 * @LastEditTime: 2023-08-28 10:31:47
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-system-banner-edit">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        ref="subForm"
        :rules="subFormRules"
        label-width="140px"
      >
        <lb-classify-title title="基础信息"></lb-classify-title>
        <el-form-item label="服务名称" prop="title">
          <el-input
            v-model="subForm.title"
            maxlength="15"
            show-word-limit
            placeholder="请输入服务名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="cate_id">
          <el-select
            v-model="subForm.cate_id"
            multiple
            collapse-tags
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in base_cate"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="send_type">
          <el-checkbox-group
            v-model="subForm.send_type"
            @change="changeCheckBox"
          >
            <div
              v-for="(item, index) in base_sendtype"
              :key="index"
              :style="{
                display: 'inline-block',
                marginLeft: index === 0 ? 0 : '15px'
              }"
            >
              <el-checkbox :label="item.title"></el-checkbox>
              <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 400 * 400</lb-tool-tips>
        </el-form-item>
        <el-form-item label="服务价格" prop="price">
          <el-input v-model="subForm.price" placeholder="请输入服务价格"
            ><template slot="append">元</template></el-input
          >
        </el-form-item>
        <el-form-item label="物料费" prop="material_price">
          <el-input v-model="subForm.material_price" placeholder="请输入物料费">
            <template slot="append">元</template></el-input
          >
          <lb-tool-tips
            >服务过程中消耗的物料费，例如：一次性衣物，物料费不计入{{
              $t('action.attendantName')
            }}提成</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="虚拟销售量" prop="sale">
          <el-input v-model="subForm.sale" placeholder="请输入虚拟销售量"
            ><template slot="append">人选择</template></el-input
          >
          <lb-tool-tips>该虚拟销售量=虚拟+实际销售量</lb-tool-tips>
        </el-form-item>
        <el-form-item label="服务时长" prop="time_long">
          <el-input v-model="subForm.time_long" placeholder="请输入服务时长"
            ><template slot="append">分钟</template></el-input
          >
          <lb-tool-tips>一次服务的时间段，一般为60分钟</lb-tool-tips>
        </el-form-item>
        <el-form-item label="分销返佣" prop="com_balance">
          <el-input v-model="subForm.com_balance" placeholder="请输入分销返佣">
            <template slot="append">%</template>
          </el-input>
          <lb-tool-tips>实际支付金额的百分比</lb-tool-tips>
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            :min="0"
            :controls="false"
            v-model="subForm.top"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <block v-if="routesItem.auth.member">
          <lb-classify-title title="会员信息"></lb-classify-title>
          <el-form-item label="会员专享" prop="member_service">
            <el-radio-group v-model="subForm.member_service">
              <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
              <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
            </el-radio-group>
            <lb-tool-tips
              >开启之后，该服务只能是指定等级会员可下单</lb-tool-tips
            >
          </el-form-item>
          <el-form-item
            label="指定会员等级专享"
            prop="service_level"
            v-if="subForm.member_service"
          >
            <el-select
              v-model="subForm.service_level"
              multiple
              collapse-tags
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in base_service_level"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </block>
        <lb-classify-title title="其他信息"></lb-classify-title>
        <el-form-item :label="'关联' + $t('action.attendantName')" prop="coach">
          <lb-button
            type="primary"
            icon="el-icon-plus"
            @click="toShowDialog('coach')"
            >选择{{ $t('action.attendantName') }}</lb-button
          >
          <lb-button
            class="ml-lg"
            type="danger"
            icon="el-icon-plus"
            @click="toShowDialog('price')"
            v-if="subForm.coach && subForm.coach.length > 0"
            >批量设置服务价格</lb-button
          >
          <el-table
            :data="subForm.coach"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            :height="subForm.coach.length > 5 ? 550 : ''"
            class="mt-lg"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="work_img" label="头像">
              <template slot-scope="scope">
                <lb-image :src="scope.row.work_img" />
              </template>
            </el-table-column>
            <el-table-column
              prop="coach_name"
              label="姓名"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="admin_name"
              label="所属代理商"
            ></el-table-column>
            <el-table-column prop="price" label="价格" min-width="150">
              <template slot="header" slot-scope="scope">
                <div style="margin-top: 7px">
                  价格<lb-tool-tips padding="10"
                    >选择{{
                      $t('action.attendantName')
                    }}点击确认后，该价格默认为服务价格
                    <div class="mt-sm">
                      若没有填写服务价格或者服务价格填写错误则默认为0
                    </div></lb-tool-tips
                  >
                </div>
              </template>
              <template slot-scope="scope">
                <el-input-number
                  size="small"
                  style="width: 150px"
                  v-model="scope.row.price"
                  :precision="2"
                  :controls="false"
                  :min="0"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div class="table-operate">
                  <lb-button
                    size="mini"
                    plain
                    type="danger"
                    @click="confirmDel(scope.row.id)"
                    >{{ $t('action.delete') }}</lb-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <lb-button
            type="primary"
            @click="submitFormInfo('sub')"
            v-preventReClick
            >{{ $t('action.submit') }}</lb-button
          >
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog
        :title="'关联' + $t('action.attendantName')"
        :visible.sync="showDialog.coach"
        width="800px"
        center
      >
        <el-form
          :inline="true"
          :model="searchForm"
          ref="searchForm"
          label-width="70px"
        >
          <el-form-item label="输入查询" prop="name">
            <el-input
              v-model="searchForm.name"
              :placeholder="
                '请输入' + $t('action.attendantName') + '姓名/手机号'
              "
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="work_img" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.work_img" />
            </template>
          </el-table-column>
          <el-table-column prop="coach_name" label="姓名"></el-table-column>
          <el-table-column
            prop="admin_name"
            label="所属代理商"
          ></el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.page"
          :pageSize="searchForm.limit"
          :total="total"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.coach = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <el-dialog
        title="批量设置服务价格"
        :visible.sync="showDialog.price"
        width="600px"
        center
      >
        <el-form
          :inline="true"
          :model="priceForm"
          ref="priceForm"
          :rules="subFormRules"
          label-width="100px"
        >
          <el-form-item label="服务价格" prop="price">
            <el-input
              v-model="priceForm.price"
              placeholder="请输入服务价格"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.price = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('price')"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    let checkServiceMember = (rule, value, callback) => {
      let { service_level: smember = 0 } = this.subForm
      if (smember && value.length === 0) {
        callback(new Error(`请选择指定会员等级专享`))
      } else {
        callback()
      }
    }
    return {
      navTitle: '',
      base_cate: [],
      base_service_level: [],
      base_sendtype: [
        {
          title: '上门',
          key: 'is_door'
        }
      ],
      subForm: {
        id: '',
        title: '',
        sub_title: '',
        cate_id: [],
        send_type: [],
        is_door: 0,
        is_store: 0,
        cover: [],
        price: '',
        material_price: '',
        sale: '',
        true_sale: '',
        time_long: '',
        com_balance: '',
        member_service: 0,
        service_level: [],
        top: 0,
        coach: [],
        status: 1,
        is_add: 1
      },
      subFormRules: {
        title: { required: true, validator: this.$reg.isNotNull, text: '服务名称', reg_type: 2, trigger: 'blur' },
        sub_title: { required: true, validator: this.$reg.isNotNull, text: '副标题', reg_type: 2, trigger: 'blur' },
        send_type: { required: true, type: 'array', message: '请选择服务方式', trigger: 'blur' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: ['blur', 'change'] },
        price: { required: true, validator: this.$reg.isMoney, text: '服务价格', trigger: 'blur' },
        material_price: { required: true, validator: this.$reg.isMoney, text: '物料费', trigger: 'blur' },
        sale: { required: true, validator: this.$reg.isNum, trigger: 'blur' },
        time_long: { required: true, validator: this.$reg.isNum, reg_type: 2, trigger: 'blur' },
        com_balance: { required: true, validator: this.$reg.isPercent, text: '分销返佣', trigger: 'blur' },
        member_service: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        service_level: { required: true, validator: checkServiceMember, trigger: 'blur' },
        top: { required: true, type: 'number', message: '请输入排序值', trigger: 'blur' },
        coach: { required: true, type: 'array', message: '请选择关联' + this.$t('action.attendantName'), trigger: 'blur' }
      },
      priceForm: {
        price: ''
      },
      priceFormRules: {
        init_price: { required: true, validator: this.$reg.isMoney, text: '服务价格', trigger: 'blur' }
      },
      searchForm: {
        page: 1,
        limit: 10,
        status: 2,
        name: ''
      },
      total: 0,
      loading: false,
      tableData: [],
      multipleSelection: [],
      showDialog: { coach: false, price: false }
    }
  },
  async created () {
    let { id } = this.$route.query
    await this.getBaseInfo()
    if (id) {
      this.subForm.id = id
      this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.ServiceBellEdit' : 'menu.ServiceBellAdd')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getBaseInfo () {
      let { store, member } = this.routesItem.auth
      let cate = []
      let smember = []
      if (member) {
        let [c, m] = await Promise.all([this.$api.service.cateSelect(), this.$api.member.levelSelect({ is_service: 1 })])
        cate = c.data
        smember = m.data
      } else {
        let { data } = await this.$api.service.cateSelect()
        cate = data
      }
      this.base_cate = cate
      this.base_service_level = smember
      if (store) {
        this.base_sendtype.push(
          {
            title: '到店',
            key: 'is_store'
          })
      }
    },
    getCover (img) {
      this.subForm.cover = img
    },
    /**
     * @name: 详情
     * @param {*} id
     */
    async getDetail (id) {
      let { code, data } = await this.$api.service.serviceInfo({ id })
      if (code !== 200) return
      data.cover = [{ url: data.cover }]
      data.service_level = data.service_level.length > 0 ? data.service_level.map(item => {
        return item.id
      }) : []
      let { store } = this.routesItem.auth
      if (!store && data.is_store) {
        data.is_store = 0
      }
      let checkItem = []
      this.base_sendtype.map(item => {
        if (data[item.key] === 1) {
          checkItem.push(item.title)
        }
      })
      data.send_type = checkItem
      for (let i in this.subForm) {
        this.subForm[i] = data[i]
      }
    },
    changeCheckBox (e) {
      this.base_sendtype.map(item => {
        this.subForm[item.key] = e.includes(item.title) ? 1 : 0
      })
    },
    async toShowDialog (key) {
      if (key === 'coach') {
        this.searchForm.name = ''
        await this.getTableDataList()
      } else {
        this.priceForm = { price: '' }
      }
      this.showDialog[key] = !this.showDialog[key]
    },
    resetForm (form) {
      this.$refs[form].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let { code, data } = await this.$api.technician.coachList(this.searchForm)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleDialogConfirm () {
      if (this.multipleSelection.length === 0) {
        this.$message.error(`请选择${this.$t('action.attendantName')}`)
        return
      }
      let coach = JSON.parse(JSON.stringify(this.subForm.coach))
      let arr1 = coach.length > 0 ? coach.map(item => { return item.id }) : []
      let { price } = this.subForm
      let reg = /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      this.multipleSelection.map(item => {
        item.price = price && reg.test(price) ? price : 0
        if (arr1.includes(item.id)) return
        coach.push(item)
      })
      this.subForm.coach = coach
      this.showDialog.coach = false
    },
    confirmDel (id) {
      let index = this.subForm.coach.findIndex(item => {
        return item.id === id
      })
      this.subForm.coach.splice(index, 1)
    },
    /**
     * @name: 新增/编辑
     * @param {*}
     */
    submitFormInfo (key) {
      let flag = true
      this.$refs[`${key}Form`].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this[`${key}Form`]))
        if (key === 'price') {
          let datas = JSON.parse(JSON.stringify(this.subForm))
          datas.coach.map(item => {
            item.price = subForm.price
          })
          this.subForm = datas
          this.showDialog[key] = false
          return
        }
        subForm.cover = subForm.cover[0].url
        let arr = subForm.coach.map(item => {
          return { coach_id: item.id, price: item.price || 0 }
        })
        subForm.coach = arr
        delete subForm.send_type
        let modelMethod = subForm.id ? 'serviceUpdate' : 'serviceAdd'
        this.$api.service[modelMethod](subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
            this.$router.back(-1)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-system-banner-edit {
  width: 100%;
  .el-form {
    width: 100%;
    .el-select,
    .el-input-number,
    .el-input {
      width: 300px;
    }
    .el-textarea {
      width: 600px;
    }
  }
}
</style>
